package com.example.mobilesafe.service;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.format.Formatter;
import android.widget.RemoteViews;

import com.example.mobilesafe.R;
import com.example.mobilesafe.dao.ProcessInfoDao;
import com.example.mobilesafe.provider.MyAppWidgetProvider;

import java.util.Timer;
import java.util.TimerTask;

public class UpdateWidgetService extends Service {

    private Timer mTimer;
    private InnerReceiver mInnerReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        // 管理进程总数和可用内存数的更新（定时器）
        startTimer();

        // 注册监听锁屏/解锁状态的广播接收者
        IntentFilter intentFilter = new IntentFilter();
        // 开锁Action
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        // 解锁Action
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);

        // 绑定广播接收器的接收条件
        mInnerReceiver = new InnerReceiver();
        registerReceiver(mInnerReceiver,intentFilter);
    }

    /**
     * 监听到锁屏/解锁状态的广播接收者内部类
     */
    private class InnerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
                // 开启定时更新任务
                startTimer();
            }else {
                // 关闭定时更新任务
                cancelTimerTask();
            }
        }
    }

    /**
     * 关闭定时器的任务
     */
    private void cancelTimerTask() {
        // Timer中的cancel()就是取消定时任务的方法
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null; // 置空以此回收
        }
    }

    /**
     * 开启一个定时器
     */
    private void startTimer() {
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // UI定时刷新
                updateAppWidget();
            }
        }, 0, 5000);
    }

    /**
     * 更新窗口小部件中的信息
     */
    private void updateAppWidget() {
        // 1.获取AppWidget对象
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
        // 2.获取窗体小部件布局转换成的view对象
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.process_widget);
        // 3.给窗体小部件设置view对象，内部控件赋值
        remoteViews.setTextViewText(R.id.tv_process_count,"进程总数：" + ProcessInfoDao.getProcessCount(this));
        // 4.显示可用内存大小
        String strAcailSpace = Formatter.formatFileSize(this, ProcessInfoDao.getAvailSpace(this));
        remoteViews.setTextViewText(R.id.tv_process_memory,"可用内存：" + strAcailSpace);

        // 5.点击窗体小部件，进入应用
        Intent intent = new Intent("android.intent.action.HOME");
        intent.addCategory("android.intent.category.DEFAULT");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.ll_root,pendingIntent);
        // 6.通过延期意图发送广播，在广播接收者中杀死进程
        Intent broadCastIntent = new Intent("android.intent.action.KILL_BACKGROUND_PROCESS");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, broadCastIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btn_clear,broadcast);

        // 7.通知AppWidget进行更新
        ComponentName componentName = new ComponentName(this, MyAppWidgetProvider.class);
        appWidgetManager.updateAppWidget(componentName,remoteViews);

    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mInnerReceiver != null){
            unregisterReceiver(mInnerReceiver);
        }
        // 停止定时器任务
        cancelTimerTask();
    }
}